<template>
  <div class="create-page">
    <div class="warp">
      <div class="create-share">
          <a href="/pages/create/main">
            <span class="create">
              <i class="iconfont">&#xe629;</i> 发起新团购
            </span>
          </a>
        <button class="share btn-reset" open-type="share"><i class="iconfont">&#xe668;</i> 分享</button>
      </div>
      <div class="info">
        <div class="log">
          <img :src="office.avatarUrl" mode="aspectFit" class="img">
          <span class="state">{{groupInfo.preStatus}}</span>
        </div>
        <div class="pInfo">
          <h3 class="name">{{office.nickName}}</h3>
          <p class="time">创建时间:  {{groupInfo.createTime}}</p>
        </div>
      </div>
      <p class="p-info">{{groupInfo.description}}</p>
      <div class="img-group">
        <div class="img-list">
          <div class="item" v-for="item in imgList" :key="item" @click="previewImage(item)">
            <img :src="item" mode="aspectFill">
          </div>
        </div>
      </div>

      <h3 class="block-title">商品列表</h3>
      <ul class="product-list">
        <li class="item" v-for="(value, index) in productList" :key="index">
          <span class="n1"><i>{{index + 1}}</i>{{value.title}}</span>
          <div class="p-count">
            <span class="n2">单价 {{value.price}}元</span>
            <span class="n3">已售 {{value.sale ? value.sale : 0}}</span>
            <span class="n4">
              <em>{{value.buyNum}}</em>
              <img src="/static/img/btn_remove_1.png" mode="aspectFit" class="down" @click="productDown(value.productId)" />
              <img src="/static/img/btn_add_1.png" mode="aspectFit" class="add" @click="productAdd(value.productId)" />
            </span>
          </div>
        </li>
      </ul>
      <div v-show="showList">
        <h3 class="block-title">报名统计</h3>
        <div class="baoming">
          <div class="item" v-for="(item, $index) in userBuyList" :key="$index">
            <div class="n1">
              <img :src="item.userImg ? item.userImg : '/static/img/mine.png'" mode="aspectFit">
              <em>{{item.userName ? item.userName : '--'}}</em>
            </div>
            <div class="n2" v-for="(sub, $ss) in item.product" :key="$ss">
              <p class="fl">{{sub.title}}</p>
              <p class="fr">{{'数量'}} <i>{{sub.sales}}</i></p>
            </div>
            <div class="n2">总价： {{item.count}}</div>
          </div>
        </div>
        
      </div>
      <h3 class="block-title">报名商品总数</h3>
      <div class="sales-info">
        <div class="p1" v-for="(item, $index) in userBuyCount" :key="$index">
          <p class="fl">{{item.title}}</p>
          <p class="fr">{{item.sales}}</p>
        </div>
      </div>
    </div>
     <div class="btn-create">
      <form @submit="submit" report-submit="true" :class="groupInfo.preStatus == '已截止' ? 'disable' : ''">
        <button formType="submit" class="btn-reset">{{submitName}}</button>
        <img src="/static/img/btn_back.png">
      </form>
    </div>
    
    <div class="share-warp" @click="clickEvent('close')" v-if="showShare">
      <div class="share-con">
        <div class="title">是否分享该团购？</div>
        <div class="btn-group">
          <button class="close btn-reset close" @click="clickEvent('cancle')">取消</button>
          <button class="close btn-reset share" open-type="share" @click="clickEvent('success')">分享</button>
        </div>
      </div>
    </div>

    <cover :config="{title: submitName+'成功'}" v-if="showCover"></cover>
  </div>
</template>

<script>
import { host } from '@/utils/conf'
import Cover from '@/components/cover'
import { timeStamp, userLogin } from '@/utils/index'
export default {
  name: '',
  data () {
    return {
      imgList: [],
      selectTime: '',
      endTimeShow: false,
      groupInfo: {},
      query: {},
      showCover: false,
      submitName: '参团',
      office: {}, //团张信息
      productList: [], //产品列表
      userBuyList: {}, //报名统计
      userBuyCount: [], //商品总数
      showShare: false
    }
  },
  components: {
    Cover
  },
  computed: {
    showList () {
      return Object.keys(this.userBuyList).length
    }
  },
  methods: {
    async requestData () {
      var that = this
      this.imgList = []
      var userBuyList = {}
      var userBuyCount = []

      wx.showToast({
        icon: 'loading',
        title: '请求中',
        duration: 50000
      })
      //获取团购信息
      var groupInfo = await this.$request({
        url: '/GroupBuyBackendV1/groupBuyInfo/' + that.query.groupId
      })
      var images =  groupInfo.images.split(',')
      for (var i in images) {
        this.imgList.push(host + '/wetousuPhoto/' + images[i])
      }
      groupInfo.createTime = timeStamp(groupInfo.createTime)
      this.groupInfo = groupInfo;

      //查找用户信息
      var office = await this.$request({
        url: '/GroupBuyBackendV1/user/' + that.groupInfo.createUserId
      })
      this.office = JSON.parse(office.userInfo)

      //获取该团购产品信息
      var productList = await this.$request({
        url: '/GroupBuyBackendV1/getProductListByGroupId/' + that.query.groupId
      })
      //默认购买分数
      productList.forEach(function(item, index) {
        item.buyNum = 0
      })
      //再获取某个产品的销售数量
      var productSale = await this.$request({
        url: '/GroupBuyBackendV1/groupOrderByGroupId/' + that.query.groupId
      })
      wx.hideToast()
    
      if (productSale.length) {
        //获取产品销量
        var saleLength = {}
        for (var i in productSale) {
          if (!saleLength[productSale[i].productId]) {
            saleLength[productSale[i].productId] = 0
          }
          saleLength[productSale[i].productId] += productSale[i].count

          //当前用户是否已经报名
          if (productSale[i].userId == that.userId) {
            that.submitName = '修改'
          }
        }
        productList.forEach(function(item, index) {
          //产品销售数量
          if (saleLength[item.productId]) {
            item.sale = saleLength[item.productId]
          }
          //自己购买信息
          // if (item.userId == that.userId) {
            for (var i in productSale) {
              if (productSale[i].userId == that.userId && productSale[i].productId == item.productId) {
                item.buyNum = productSale[i].count
                item.updateId = productSale[i].groupOrderId
              }
            }
          // }
        })
      }
      //获取产品列表对应的空值
      function getProduct () {
        var data = []
        productList.forEach(function(item, index) {
          data.push({
            sales: 0,
            title: item.title,
            price: item.price,
            productId: item.productId
          })
        })
        return data
      }
      userBuyCount = getProduct()
      //获取统计 相同uid数据拼接
      productList.forEach(function(item, index) {
        var pid = item.productId
        var sale = item.sale
        var title = item.title
        //循环一次寻找用户对应的id
        productSale.forEach(function(u, ss) {
          if (!userBuyList[u.userId]) {
            userBuyList[u.userId] = {
              count: 0,
              userId: u.userId,
              userName: u.userNickName,
              userImg: u.userImageUrl,
              product: getProduct()
            }
          }
          if (pid == u.productId) {
            userBuyList[u.userId].product.forEach(function(item, index) {
              if (item.productId == u.productId) {
                item.sales = u.count
              }
            })
            userBuyCount.forEach(function(item, index) {
              if (item.productId == u.productId) {
                item.sales += u.count
              }
            })
            // userBuyList[u.userId].product[pid].sales = u.count
            // userBuyCount[pid].sales += u.count
          }
        })
      })

      for (var u in userBuyList) {
        var ui = userBuyList[u]
        if (ui.product) {
          for (var s in ui.product) {
            var pi = ui.product[s]
            if (pi.sales > 0) {
              ui.count += pi.sales*pi.price
            }
          }
        }
      }
    
      this.userBuyList = userBuyList
      this.userBuyCount = userBuyCount
      this.productList = productList
      wx.setNavigationBarTitle({
        title: that.groupInfo.title
      })
    },
    groupStatusFn () {
      var that = this

      //截止时间判断
      if (this.groupInfo.dueDataTime) {
        if (this.groupInfo.dueDataTime > new Date().getTime()) {
          this.groupInfo.preStatus = '已截止'
        }
      }
    },
    productDown (pid) {
      if (pid) {
        for (var i in this.productList) {
          if (this.productList[i].productId == pid) {
            if (this.productList[i].buyNum == 0) {
              //如果为零则不能减少
              wx.showToast({
                icon: 'none',
                title: '商品数量不能小于0'
              })
            } else {
              this.productList[i].buyNum--
            }
            break;
          }
        }
      }
    },
    productAdd (pid) {
      if (pid) {
        for (var i in this.productList) {
          if (this.productList[i].productId == pid) {
            this.productList[i].buyNum++
            break;
          }
        }
      }
    },
    previewImage (url) {
      wx.previewImage({
        urls: [url]
      })
    },
    //提交订单
    async submit (e) {
      //判断是否选择商品
      var that = this;
      var selectItem = false
      var formId = e.target.formId
      var userJson = wx.getStorageSync('userJson')

      //变灰
      if (this.groupInfo.preStatus == '已截止') {
        wx.showToast({
          icon: 'none',
          title: '该团已截止'
        })
        return
      }

      for (var i in this.productList) {
        if (this.productList[i].buyNum > 0) {
          selectItem = true
        }
      }
      if (!selectItem) {
        wx.showToast({
          icon: 'none',
          title: '请在商品列表选择需要购买商品的个数'
        })
        return;
      }

      wx.showToast({
        icon: 'loading',
        title: '请求中...',
        duration: 50000
      })
      if (userJson) {
        userJson = JSON.parse(userJson)
      } else {
        console.log('用户信息不完整')
      }
      for (var i = 0; i < this.productList.length; i++ ) {
        var item = this.productList[i]
        var data = {
          formId: formId,
          status: '开团中',
          preStatus: '开团中',
          count: item.buyNum,
          productId: item.productId,
          groupBuyId: that.query.groupId,
          userNickName: userJson.nickName,
          userImageUrl: userJson.avatarUrl,
          userId: wx.getStorageSync('userId'),
        }
        //当前用户已购买，为更新
        if (item.updateId) {
          data.groupOrderId = item.updateId
        }
        var res = await this.$request({
          url: '/GroupBuyBackendV1/groupOrder',
          data: data,
          type: 'POST'
        })
      }
      wx.hideToast();
      this.showToast()
      
    },
    showToast () {
      var that = this
      
      setTimeout(function() {
        that.showCover = !that.showCover
        //该用户没有填写详细地址
        if (!wx.getStorageSync('userInfo')) {
          wx.showModal({
            content: '前去填写收货地址',
            success: function(res) {
              if (res.confirm) { 
                wx.navigateTo({
                  url: '/pages/user-info/main?back=1&groupId='+ that.query.groupId
                })
              } else {
                that.requestData()
              }
            }
          })
        } else {
          that.requestData()
        }
      }, 1500)
      that.showCover = !that.showCover
    },
    clickEvent () {
      this.showShare = false
    }
  },
  mounted () {
    userLogin()
    this.userId = wx.getStorageSync('userId')
    this.query = this.$root.$mp.query
    //如果新创建则显示分享弹窗
    if (this.query.newCreate) {
      this.showShare = true
    }
    this.requestData()
    this.groupStatusFn()
  },
  onUnload () {
    this.imgList = []
    this.selectTime = ''
    this.endTimeShow = false
    this.groupInfo = {}
    this.query = {}
    this.showCover = false
    this.submitName = '参团'
    this.office = {} //团张信息
    this.productList = [] //产品列表
    this.userBuyList = {} //报名统计
    this.userBuyCount = [] //商品总数
  },
  onShareAppMessage () {
    var that = this
    return {
      title: that.groupInfo.title,
      path: '/pages/group-detail/main?groupId=' + that.query.groupId,
      imageUrl: wx.getStorageSync('shareImg'),
    }
  }
}
</script>

<style lang="stylus" scoped>
  .create-page {
    padding-bottom: 100rpx
    .sales-info {
      padding: 12rpx 0
      font-size: 28rpx
      color: #131313
      .p1 {
        overflow: hidden
        line-height: 54rpx
      }
      .fl {
        float: left
      }
      .fr {
        float: right
      }
    }
    .baoming {
      margin-top: 10rpx
      .item {
        overflow: hidden;
        padding-top: 16rpx
      }
      .res {
        color: #b2b2b2
        font-size: 22rpx
        line-height: 66rpx
        padding-left: 360rpx
        overflow: hidden
        .p1,.p2 {
          float: left
          width: 50%
        }
      }
      .n1 {
        color: #131313
        overflow: hidden
        position: relative
        width: 100%
        img {
          width: 84rpx
          height: 84rpx
          float: left
          border-radius: 50%
          position: absolute
        }
        em {
          float: left
          font-size: 32rpx
          line-height: 84rpx
          margin-left: 112rpx
        }
      }
      .n2 {
        font-size: 24rpx
        margin-left: 112rpx
        line-height: 42rpx
        overflow: hidden
        .fl {
          float: left
        }
        .fr {
          float: right
          padding-right: 60rpx
          position: relative

          i {
            right: 0
            top: 0
            position: absolute
          }
        }
      }
    }
    .product-list {
      margin-top: 10rpx
      .item {
        overflow: hidden
        padding-left: 42rpx
        position: relative

        .n2,.n3,.n4 {
          float: left
          font-size: 26rpx
          color: #131313
          height: 73rpx
          line-height: 72rpx
        }
        .n1 {
          font-size: 28rpx
          color: #131313
          i {
            position: absolute
            left: 0
            line-height: 62rpx
          }
        }
        .n2 {
          width: 260rpx
        }
        .n3 {
          width: 190rpx
        }
        .n4 {
          width: 190rpx
          position: relative
          .down,.add {
            width: 48rpx
            height: 48rpx
            position: absolute
            top: 50%
            transform: translateY(-50%)
          }
          .down {
            left: 0
          }
          .add {
            right: 0
          }
          em {
            font-size: 34rpx
            display: block
            margin: 0 auto
            text-align: center
          }
        }
      }
    }
    .create-share {
      overflow: hidden
      i {
        display: inline;
      }
      span,button {
        color: #fff
        font-size: 28rpx
        line-height: 58rpx
        background: #f88e4e
        text-align: center
        border-radius: 29rpx
      }
      .create {
        float: left
        width: 224rpx
      }
      .share {
        width: 140rpx
        float: right
      }
    }
    .info {
      overflow: hidden
      margin: 64rpx 0 30rpx
      .log {
        float: left
        width: 96rpx
        height: 96rpx
        overflow: hidden
        position: relative
        border-radius: 16rpx
        box-sizing: border-box
        .img {
          width: 96rpx
          height: 96rpx
        }
        .state {
          color: #fff
          text-align: center
          font-size: 15rpx
          position: absolute
          left: 0
          bottom: 0
          width: 100%
          padding: 6rpx 0 0 5rpx
          background: rgba(0,0,0,.6)
        }
      }
      .pInfo {
        float: left
        margin-left: 20rpx
        .name {
          margin-top: 10rpx
          font-size: 36rpx
          height: 54rpx
        }
        .time {
          margin-top: 6rpx
          color: #d3d3d3
          font-size: 22rpx
        }
        .btn {
          top: 50%
          transform: translateY(-50%)
          right: 30rpx
          width: 120rpx
          text-align: center
          line-height: 62rpx
          position: absolute
          font-size: 26rpx
          color: #fff
          border-radius: 31rpx
          background: #ff8942
        }
      }
    }
    .img-list {
      overflow: hidden
      .item {
        width: 114rpx
        height: 114rpx
        float: left
        position: relative;
        img {
          width: 114rpx
          height: 114rpx
          border-radius: 20rpx
        }
      }
      .item + .item{
        margin-left: 28rpx
      }
    }
    .warp {
      padding: 16rpx 32rpx
    }

    .p-info {
      color: #131313
      font-size: 28rpx
      padding-top: 20rpx
      border-top: 1px solid #f4f4f4
    }
    .img-group {
      margin-top: 100rpx
    }
    .block-title {
      color: #131313
      font-size: 34rpx
      margin-top: 70rpx
      line-height: 48rpx
      padding-bottom: 12rpx
      border-bottom: 1px solid #f4f4f4
    }
    .btn-create {
      width: 100%
      bottom: 0
      left: 0
      position: fixed
      img {
        height: 94rpx
        width: 100%
      }
      form {
        display: block
        width: 100%
        height: 94rpx
      }
      form.disable {
        background: #ccc
        img {
          display: none
        }
      }
      button {
        color: #fff
        z-index: 10
        position: absolute
        width: 100%
        height: 94rpx
        text-align: center
        line-height: 94rpx
        font-size: 34rpx
        left: 0
        top: 0
      }
    }
  }
  .share-warp {
    position: fixed
    left: 0
    right: 0
    top: 0
    bottom: 0
    background: rgba(0,0,0,0.6)
  }
  .share-con {
    width: 600rpx
    color: #131313
    background: #fff
    margin: 50% auto 0 auto
    .title {
      height: 180rpx
      padding: 0 20rpx
      line-height: 180rpx
      text-align: center
      font-size: 28rpx
      box-sizing: border-box
    }
    .btn-group {
      overflow: hidden
      border-top: 1px solid #ccc
      button {
        width: 50%
        float: left
        height: 100rpx
        font-size: 30rpx
        text-align: center
        line-height: 100rpx
      }
      .share {
        color: #1AAD16
        border-left: 1px solid #ccc
      }
    }
  }
</style>
